package cn.yaboya.basic.interceptor;


import cn.yaboya.basic.annotation.PreAuthorize;
import cn.yaboya.system.mapper.PermissionMapper;
import cn.yaboya.user.domain.Logininfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 登录拦截器
 * @Author: Mr.She
 * @Version: 1.0
 * @Date:  2022/6/13 16:54
 */
@Component // 需要加上此注解将当前登录拦截器交给spring管理
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");

        System.out.println("第四个拦截器");
        // 获取无状态token
        String token = request.getHeader("token");
        // 判断前端发送过来的是否含有token  如果有就进入下一步 放行的业务
        if(!StringUtils.isEmpty(token)){
            // 2.1跟进token取得redis的用户信息
            Object logininfo = redisTemplate.opsForValue().get(token);
            // 2.2.如果用户信息不为空，那么刷新Redis中token有效期登录成功  重新刷新时间
            if (logininfo != null){
                // 如果用户信息不为空，我们继续判断用户是否拥有访问此URL的权限
                // 将Object类型的logininfo拷贝到Logininfo对象中
                Logininfo logininfoTmp = new Logininfo();
                BeanUtils.copyProperties(logininfo,logininfoTmp);
                // 判断是否为员工
                /*if (logininfoTmp.getType() == 0){
                    // 进入此判断则代表是员工 获取到到用户访问接口我们自定义的@PreAuthorize注解的sn值，用来确定用户访问的是那个URL权限
                    // 得到本次请求的方法对象
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (preAuthorize != null) {
                        String permissionSn = preAuthorize.sn();
                        List<String> ownPermissions = permissionMapper.loadOwnPermissionByLogininId(logininfoTmp.getId());
                        if(!ownPermissions.contains(permissionSn)) {
                            // 3.3.获取到打印流,并设置响应数据
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 刷新关流
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }*/
                redisTemplate.opsForValue().set(
                        token,
                        logininfo,
                        30,
                        TimeUnit.MINUTES
                );
                return true;
            }
            // 3.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理

            // 3.3.获取到打印流,并设置响应数据
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
            // 刷新关流
            // 3.4.刷新、关流
            writer.flush();
            writer.close();
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);

    }
}
